import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:go_router/go_router.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:zywz/widgets/financial_card.dart';
import 'package:zywz/utils/common_ui.dart';
import 'package:zywz/config/app_colors.dart';

import '../../bloc/service/service_bloc.dart';
import '../../dialog/dialog1.dart';

// 直接使用AppColors静态类

class ServiceOrderListPage extends StatefulWidget {
  const ServiceOrderListPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _ServiceOrderListPageState();
  }

}

class _ServiceOrderListPageState extends State<ServiceOrderListPage> {


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      context.read<ServiceBloc>().add(ServiceOrderListEventInit());
    });
  }

  @override
  Widget build(BuildContext context) {
    // 模拟服务订单数据

    return Scaffold(
      appBar: AppBar(
        centerTitle: true, // 这行是关键
        backgroundColor: AppColors.primaryColor,
        title: const Text(
          '服务',
          style: TextStyle(
            color: AppColors.textWhite,
            fontSize: 18.0,
            fontWeight: FontWeight.bold,
          ),
        ),
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => Navigator.pop(context),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(16.0),
        child: BlocConsumer<ServiceBloc, ServiceState>(
          buildWhen: (previous, current) => current is ServiceOrderListSuccessState || current is ServiceNoDataState,
          listener: (BuildContext context, state) {  },
          builder: (BuildContext context, state) {
            if(state is ServiceOrderListSuccessState){
              return Container(
                decoration: BoxDecoration(
                  color: Colors.white,
                  border: Border.all(color: Color(0xFF4DD0E1)),
                  borderRadius: BorderRadius.circular(3.0),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [
                    // 表格标题
                    Container(
                      color: Colors.white,
                      child: Row(
                        children: [
                          Expanded(
                            flex: 7,
                            child: Padding(
                              padding: const EdgeInsets.only(left: 16.0),
                              child: Text('服务名称', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF4DD0E1))),
                            ),
                          ),
                          Container(
                            height: 36,
                            width: 1,
                            color: Color(0xFF4DD0E1),
                          ),
                          Expanded(
                            flex: 3,
                            child: Center(child: Text('服务状态', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF4DD0E1)))),
                          ),
                          Container(
                            height: 36,
                            width: 1,
                            color: Color(0xFF4DD0E1),
                          ),
                          Expanded(
                            flex: 3,
                            child: Align(
                              alignment: Alignment.centerRight,
                              child: Center(child: Text('操作', style: TextStyle(fontWeight: FontWeight.bold, color: Color(0xFF4DD0E1)))),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      height: 1,
                      width: double.infinity,
                      color: Color(0xFF4DD0E1),
                    ),
                    // 表格内容
                    ...List.generate(
                        state.data?.length ?? 0, (index) {
                      final order = state.data?[index];
                      print('order: ${order?.serviceName}');
                      print('order: ${order?.orderStatus}');
                      print('order: ${order?.orderStatus == 3 ? '已支付' : order?.orderStatus == 2 ? '已取消' : '待支付'}');

                      final statusColor = order?.orderStatus == '2' ? AppColors.textPrimary : AppColors.textSecondary;
                      return Column(
                        children: [
                          if (index > 0) const Divider(thickness: 1, height: 1, color:  Color(0xFF4DD0E1)),
                          IntrinsicHeight(
                            child: Row(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Expanded(
                                  flex: 7,
                                  child: Padding(
                                    padding: const EdgeInsets.only(left: 16.0),
                                    child: Text(order?.serviceName ?? '', style: TextStyle(color: AppColors.textPrimary)),
                                  ),
                                ),
                                Container(
                                  height: double.infinity,
                                  width: 1,
                                  color: Color(0xFF4DD0E1),
                                ),
                                //orderStatus 1 待支付 2 已支付 3 已取消
                                Expanded(
                                  flex: 3,
                                  child: Center(
                                    child: Text(
                                      order?.orderStatus == 2 ? '已支付' : order?.orderStatus == 3 ? '已取消' : '待支付',
                                      style: TextStyle(color: statusColor),
                                    ),
                                  ),
                                ),
                                Container(
                                  height: double.infinity,
                                  width: 1,
                                  color: Color(0xFF4DD0E1),
                                ),
                                Expanded(
                                  flex: 3,
                                  child: Column(
                                    children: [
                                      SizedBox(height: 8),
                                      GestureDetector(
                                        behavior: HitTestBehavior.opaque,
                                        onTap: (){
                                          context.push('/service-detail',extra: order);
                                        },
                                        child: SizedBox(
                                            height: 26,
                                            width: 86,
                                            child: Container(
                                              decoration: BoxDecoration(
                                                shape: BoxShape.rectangle,
                                                color: AppColors.primaryColor,
                                                borderRadius: BorderRadius.circular(26.0),
                                              ),
                                              child: Center(
                                                child: Text('订单详情', style: TextStyle(color: AppColors.cardBackgroundColor,fontSize: 10)),
                                              ),
                                            )
                                        ),
                                      ),

                                      if(order?.reportStatus ==  "4" || order?.reportStatus == "5")
                                        Column(
                                          children: [
                                            SizedBox(height: 8),
                                            if(order?.reportStatus == '4')
                                              GestureDetector(
                                                behavior: HitTestBehavior.opaque,
                                                onTap: () async {
                                                  // 点击下载报告
                                                  final Uri _url = Uri.parse(order?.reportUrl ?? '');
                                                  if (!await launchUrl(_url)) {
                                                  throw Exception('Could not launch $_url');
                                                  }

                                                },
                                                child: SizedBox(
                                                    height: 26,
                                                    width: 86,
                                                    child: Container(
                                                      decoration: BoxDecoration(
                                                        shape: BoxShape.rectangle,
                                                        color: AppColors.primaryColor,
                                                        borderRadius: BorderRadius.circular(26.0),
                                                      ),
                                                      child: Center(
                                                        child: Text('下载报告', style: TextStyle(color: AppColors.cardBackgroundColor,fontSize: 10)),
                                                      ),
                                                    )
                                                ),
                                              ),
                                            if(order?.reportStatus == '5')
                                              SizedBox(
                                                height: 26,
                                                width: 86,
                                                child: DecoratedBox(
                                                  decoration: BoxDecoration(
                                                    shape: BoxShape.rectangle,
                                                    border: Border.all(color: AppColors.dividerColor),
                                                    borderRadius: BorderRadius.circular(26.0),
                                                  ),
                                                  child: GestureDetector(
                                                    behavior: HitTestBehavior.opaque,
                                                    onTap: (){
                                                      showPopDialog(context, order?.resultMsg ?? '', onConfirm: (){
                                                        // 点击重新支付
                                                        context.push('/company_verification');
                                                        Navigator.pop(context);
                                                      }, onCancel: (){
                                                        // 点击取消
                                                        Navigator.pop(context);
                                                      });
                                                    },
                                                    child: Center(
                                                      child: Row(
                                                        mainAxisAlignment: MainAxisAlignment.center,
                                                        crossAxisAlignment: CrossAxisAlignment.center,
                                                        children: [
                                                          Text( '失败', style: TextStyle(color: AppColors.textPrimary,fontSize: 10)),
                                                          SizedBox(width: 2),
                                                          Container(
                                                            decoration: BoxDecoration(
                                                              shape: BoxShape.circle,
                                                              color: Colors.red,
                                                            ),
                                                            height: 6,
                                                            width: 6,
                                                          ),
                                                        ],
                                                      ),
                                                    ),
                                                  ),
                                                )
                                            ),
                                          ],
                                        ),
                                      SizedBox(height: 8),
                                    ],
                                  ),
                                )
                              ],
                            ),
                          ),
                        ],
                      );
                    }
                    ),
                  ],
                ),
              );
            }else{
              return Container();
            }
          },


        ),
      ),
    );
  }






  void showPopDialog(BuildContext context, String contextText, {
    required Function() onConfirm,
    required Function() onCancel,
  }) {
    showDialog(
      context: context,
      barrierDismissible: false, // 点击外部不可关闭
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16.0),
          ),
          elevation: 0,
          backgroundColor: Colors.white,
          child: Container(
            padding: const EdgeInsets.all(24.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                const Text(
                  '提示',
                  style: TextStyle(
                    fontSize: 18.0,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 24.0),
                Text(contextText,
                  style: TextStyle(
                    fontSize: 16.0,
                    color: Color(0xFF333333),
                  ),
                  textAlign: TextAlign.center,
                ),
                const SizedBox(height: 32.0),
                Row(
                  children: [
                    Expanded(
                      child: SizedBox(
                        height: KHighLight,
                        child: ElevatedButton(
                          onPressed: onCancel,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFFE0F7FA), // 浅青色
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                            elevation: 0,
                          ),
                          child: const Text('取消', style: TextStyle(color: Color(0xFF41C7DD), fontSize: 13)),
                        ),
                      ),
                    ),
                    const SizedBox(width: 16),
                    Expanded(
                      child: SizedBox(
                        height: KHighLight,
                        child: ElevatedButton(
                          onPressed: onConfirm,
                          style: ElevatedButton.styleFrom(
                            backgroundColor: const Color(0xFF41C7DD),
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(25),
                            ),
                            elevation: 2,
                          ),
                          child: const Text('确认', style: TextStyle(color: Colors.white, fontSize: 13)),
                        ),
                      ),
                    ),
                  ],
                )
              ],
            ),
          ),
        );
      },
    );
  }




}
